<template>
    <div class="comm-wrapper">
        <div class="status-bar" :style="{'height': statusHeight}"></div>
        <div class="header">
            <text class="iconfont headerIcon" @click="back">&#xe601;</text>
            <text class="headerTextSize">选择门店</text>
            <div class="header_right"  @click="showGroupCityPush">
                <text class="ic iconfont">&#xe615;</text>
                <text class="txt">{{location}}</text>
            </div>
        </div>
        <list class="item-container">
            <refresh @refresh="loadingDown(index)"></refresh>
            <cell class="border-cell"></cell>
            <cell v-for="(demo,key) in storeList"
                class="cell"
                :key="key">
                <div class="content"  @click="goStore(demo)">
                    <!--<image class="content_img"  v-if="demo.img" :src="demo.img"></image>-->
                    <!--<image class="content_img" v-else src="bmlocal://assets/acw/car.jpg"></image>-->
                    <div>
                        <text class="content_first">{{demo.companyname}}</text>
                        <div class="content_third">
                            <text class="content_first">地址：{{demo.adress}}</text>
                        </div>
                        <div class="content_third">
                            <text class="content_four_text">距离：{{demo.distance}}千米</text>
                            <text class="iconfont content_four_phone" @click="callPhone(demo.ownerphone)">&#xe60b;</text>
                        </div>
                    </div>
                </div>
            </cell>
            <cell class="cell-button no-order" v-if="storeList.length <= 0 && showLoading == 'hide'">
                <image src="bmlocal://assets/acw/wuwangluo.png" class="noOrderImg"></image>
                <text class="noOrderTxt">暂无记录</text>
            </cell>
            <loading class="comm-loading" @loading="onloading" :display="showLoading">
                <loading-indicator class="comm-indicator" v-if="!lastPage"></loading-indicator>
                <text class="comm-indicator-text" >{{loadingText}}</text>
            </loading> 
        </list>
        <!-- push方式演示 -->
        <wxc-city ref="wxcCityPush" :style="{'margin-top': cityTop + 20}"
              :inputConfig="inputConfig"
              :animationType="animationTypePush"
              :currentLocation="location"
              :cityStyleType="cityStyleType"
              :sourceData="sourceData"
              :showNavHeader="true"
              @wxcCityItemSelected="citySelect"
              @wxcCityOnInput="cityInputChange"
              @wxcCityCanceled="cityCancel"></wxc-city>
    </div>
</template>
<script>
import { WxcButton, WxcCity } from 'weex-ui';
var amap = weex.requireModule('amap');
amap.initAmap('5442d6dc648cc739792f38c71db540c3');

export default {
    components: { WxcButton, WxcCity },
    data () {
        return {
            token: '',
            statusHeight: Number.parseInt(this.statusBarHeight || weex.config.env.statusBarHeight || 40),
            storeList: [],
            nextClick: true,
            showLoading: 'show',
            form: {
                'uid': '', // 用户id
                'carid': '',  // 汽车id
                'couponid': '',  // 优惠券id
                'ownername': '',  // 车主
                'ownerphone': '',  // 车主电话
                'type': '1',  // 服务项目 1保养  2 维修   汽车美容  1 美容  2 洗车
                'kilometer': '',  // 公里数
                'appointmentdate': '',  // 预约时间
                'appointmenttime': '',  // 预约时间
                'p1': '',  // 1 维修保养订单  2 汽车美容订单 3 车辆检测
                'storeid': '', // 商家id
                'storeName': '', // 商家名称
                "brandid": '',
                "seriesid": '',
                "styleid": '',
            },
            searchParam: {
                "latitude": "", // 纬度
                "limit": 6,
                "longitude": "", // 经度
                "order": "asc",
                "page": 1,
                "sort": "id",
                "type": 2,
                "status": 1,
                "freeze": 0,
            },
            lastPage:false,//是否是最后一页
            loadingText:'加载中 ...',
            location: '定位中',
            cityStyleType:'list',
            animationTypePush:'push', // 默认使用push方式，若使用push模式此参数可以不传
            areaData: [{
                'title': '获取中',
                'checked': true
            }],
            inputConfig: {
                autofocus: false,
                alwaysShowCancel: true,
                placeholder: '中文/拼音/首字母',
                showCancel: true
            },
            cityTop: 40,
        }
    },
    created () {
        let user = this.$storage.getSync('UserInfo')
        this.token = user.token
        this.$router.getParams().then(resData => {
            console.log(resData)
            if (resData.couponid) {
                this.form.couponid = resData.couponid
            }
            this.form.uid = resData.uid
            this.form.carid = resData.carid
            this.form.ownername = resData.ownername
            this.form.ownerphone = resData.ownerphone
            this.form.type = resData.type
            this.form.kilometer = resData.kilometer
            this.form.appointmentdate = resData.appointmentdate
            this.form.appointmenttime = resData.appointmenttime
            this.form.p1 = resData.p1
            this.form.brandid = resData.brandid
            this.form.seriesid = resData.seriesid
            this.form.styleid = resData.styleid
            let locatData = this.$storage.getSync('locatData')
            this.location = this.$storage.getSync('cityName')
            // if (this.location) {
            //     this.searchParam.latitude = locatData.locationLat
            //     this.searchParam.longitude = locatData.locationLng
            //     this.getStoreList(this.searchParam)
            // } else {
            //     this.$notice.loading.show();
            //     this.getLocation()
            // }
            this.$notice.loading.show();
            this.getLocation()
        })
    },
    methods: {
        // 返回
        back () {
            this.$router.back();
        },
        callPhone (phone) {
            this.$coms.call(phone)
        },
        // 发布买车
        next () {
            
        },
        loadingDown(index) {
        },
        onloading (event) {
            this.searchParam.page = this.searchParam.page + 1;
            this.$notice.loading.show();
            this.showLoading = 'show';
            console.log("============== :" + this.pageNum);
            if(!this.lastPage) {
                this.getStoreList(this.searchParam)
            } 
            setTimeout(() => {
                this.$notice.loading.hide();
                this.showLoading = 'hide'
            }, 600)
        },
        // 跳转店铺
        goStore (store) {
            this.form.storeid = store.id
            this.form.storeName = store.storename
            this.$router.open({
                name: 'acw.service.maintennace.store',
                type: 'PUSH',
                params: this.form
            });
        },
        // 解析数据列表
        analysisStore (list, param) {
            for (let i = 0, len = list.length; i < len; i++) {
                list[i].img = list[i].businesslicensepics.split(',')[0]
                amap.getLineDistance([param.longitude, param.latitude],[list[i].longitude, list[i].latitude], (res) => {
                    list[i].distance = (res.data.distance / 1000).toFixed(2)
                })
            }
            return list
        },
        // 查询商家列表
        getStoreList (param) {
            this.$notice.loading.show();
            let vm = this;
            this.$fetch({
                method: 'POST',    // 大写
                name: 'store.list', //当前是在apis中配置的别名，你也可以直接绝对路径请求 如：url:http://xx.xx.com/xxx/xxx
                data: param
            }).then(resData => {
                if(resData && resData.errno == 0){
                    var list = this.analysisStore(resData.data.items, param);
                    if(param.page == 1){
                        vm.storeList = [];
                    }
                    list.forEach((item, i) => {
                        vm.storeList.push(item)
                    });
                    setTimeout(() => {
                        vm.$notice.loading.hide();
                        vm.showLoading = 'hide'
                    }, 500)
                    if(resData.data && vm.storeList.length >= resData.data.total){
                        this.lastPage = true;
                        this.loadingText = '没有更多'
                    }
                }
                

            }, error => {
                // 错误回调
                setTimeout(() => {
                    vm.$notice.loading.hide();
                    vm.showLoading = 'hide'
                }, 500)
                console.log(error)
            })
        },
        showGroupCityPush () {
            this.cityStyleType = 'group'
            // 默认使用push方式，若使用push模式此参数可以不传
            this.animationTypePush = 'push'
            this.$refs['wxcCityPush'].show();
        },
        citySelect (e) {
            console.log(e);
            if(e.item.isLocation) {
                return;
            }

            this.currentCity = e.item;
            this.location = e.item.cityName;

            let SUrl = 'https://restapi.amap.com/v3/config/district?keywords=' + e.item.cityName + '&subdistrict=2&key=450bfc326ae7a1b49a2c82c3d716e2b9';

            this.$fetch({
                method: 'GET',    // 大写
                // name: 'common.getInfo', //当前是在apis中配置的别名，你也可以直接绝对路径请求 如：url:http://xx.xx.com/xxx/xxx
                url: encodeURI(SUrl),
                data: {
                    count: 1
                }
            }).then(resData => {
                if(resData.districts.length > 1 ){
                    console.log(resData.districts[1].districts);
                    // this.areaData = [];
                    this.areaData = [{
                        'title': '全部',
                        'value': '',
                        'checked': true
                    }];
                    const areaList = resData.districts[1].districts;
                    areaList.forEach( ( item, i ) => {
                        console.log( item, i );
                        let tmp = {};
                        tmp = {"title": item.name, 'value': item.name};
                        this.areaData.push(tmp);
                    } );
                } else {

                    // this.areaData = [];
                    this.areaData = [{
                        'title': '全部',
                        'value': '',
                        'checked': true
                    }];
                    const areaList = resData.districts[0].districts;
                    areaList.forEach( ( item, i ) => {
                        console.log( item, i );
                        let tmp = {};
                        
                        tmp = {"title": item.name, 'value': item.name};
                        this.areaData.push(tmp);
                    } );
                }
                

            }, error => {
                // 错误回调
                console.log(error)
                this.$notice.toast({ message: "定位失败, 请检查GPS"})
            })
            
        },
        cityInputChange (e) {
            console.log(e);
           
        },
        cityCancel (e) {
            console.log("-------------Cancel-----");
        },
        getLocation () {
            const vm = this;
            vm.$geo.get().then(data => {
                const lUrl = 'https://restapi.amap.com/v3/geocode/regeo?output=JSON&location=' + data.locationLng + ',' + data.locationLat + '&key=450bfc326ae7a1b49a2c82c3d716e2b9&radius=1000&extensions=all'
                this.searchParam.latitude = data.locationLat
                this.searchParam.longitude = data.locationLng
                this.getStoreList(this.searchParam)
                // 示例
                vm.$fetch({
                    method: 'GET',    // 大写
                    // name: 'common.getInfo', //当前是在apis中配置的别名，你也可以直接绝对路径请求 如：url:http://xx.xx.com/xxx/xxx
                    url: lUrl,
                    data: {
                        count: 1
                    }
                }).then(resData => {
                    // 成功回调
                    console.log(resData.regeocode.addressComponent.province);
                    const addr = resData.regeocode.addressComponent.province;
                    const city = resData.regeocode.addressComponent.city;
                    console.log(typeof city);
                    const ty = (typeof addr);
                    console.log(ty);
                    // const test = "新疆维吾尔自治区";
                    const reg = /(市|省|自治区)$/g;

                    if(typeof city == 'string'){
                        vm.location = city.replace(reg, "");
                    } else {
                        vm.location = addr.replace(reg, "");
                    }

                    const ZUrl = 'https://restapi.amap.com/v3/config/district?keywords=' + this.location + '&subdistrict=2&key=450bfc326ae7a1b49a2c82c3d716e2b9';

                    vm.$fetch({
                        method: 'GET',    // 大写
                        // name: 'common.getInfo', //当前是在apis中配置的别名，你也可以直接绝对路径请求 如：url:http://xx.xx.com/xxx/xxx
                        url: encodeURI(ZUrl),
                        data: {
                            count: 1
                        }
                    }).then(resData => {
                        if(resData.districts.length > 1 ){
                            console.log(resData.districts[1].districts);
                            vm.areaData = [{
                                'title': '全部',
                                'value': '',
                                'checked': true
                            }];
                            const areaList = resData.districts[1].districts;
                            areaList.forEach( ( item, i ) => {
                                console.log( item, i );
                                let tmp = {};
                                tmp = {"title": item.name, 'value': item.name};
                                vm.areaData.push(tmp);
                            } );

                        } else if (this.location == "") {
                            // vm.areaData = [];
                            vm.areaData = [{
                                'title': '全部',
                                'value': '',
                                'checked': true
                            }];
                            const areaList = resData.districts[0].districts;
                            areaList.forEach( ( item, i ) => {
                                console.log( item, i );
                                let tmp = {};
                                tmp = {"title": item.name, 'value': item.name};
                                vm.areaData.push(tmp);
                            } );
                        }


                    }, error => {
                        console.log("::::::::::::::::: 1")
                        // 错误回调
                        console.log(error)
                    })

                }, error => {
                    console.log(":::::::::::::::::2")
                    // 错误回调
                    console.log(error)
                })
            }, error => {
                console.log("::::::::::::::::: 3")
                console.log(error)
            })
        },
    }
}
</script>
<style lang="scss" src='./chosestore.scss'></style>
